package com.ysd.lis.service.lab.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.ysd.common.Result;
import com.ysd.lis.entity.SysInterface;
import com.ysd.lis.entity.SysUser;
import com.ysd.lis.entity.lab.*;
import com.ysd.lis.mapper.lab.*;
import com.ysd.lis.mapper.sys.SysInterfaceMapper;
import com.ysd.lis.request.SysParamFieldValueDto;
import com.ysd.lis.request.SysParamParam;
import com.ysd.lis.service.SysBasDictDetailService;
import com.ysd.lis.service.SysParamValueService;
import com.ysd.lis.service.lab.LabHisReqService;
import com.ysd.lis.service.lab.LabReqMainService;
import com.ysd.lis.service.lab.LabReqUnqualifiedDetailService;
import com.ysd.lis.service.lab.LabReqdetailService;
import com.ysd.util.RedisUserManager;
import com.ysd.util.ToolsUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;

/**
 * <p>
 * 不合格记录原因详情表 服务实现类
 * </p>
 *
 * @author Bai
 * @since 2024-02-04
 */
@Service
public class LabReqUnqualifiedDetailServiceImpl extends ServiceImpl<LabReqUnqualifiedDetailMapper, LabReqUnqualifiedDetail> implements LabReqUnqualifiedDetailService {

    @Autowired
    LabReqUnqualifiedMapper reqUnqualifiedMapper;
    @Autowired
    LabUnqualifiedReasonMapper unqualifiedReasonMapper;
    @Autowired
    LabReqMainMapper reqMainMapper;

    @Autowired
    LabReqStateMapper labReqStateMapper;
    @Autowired
    SysBasDictDetailService detailService;
    @Autowired
    SysInterfaceMapper sysInterfaceMapper;
    @Autowired
    LabReqMainService labReqMainService;
    @Autowired
    LabProcessSetMapper processSetMapper;
    @Autowired
    SysParamValueService sysParamValueService;
    private List<String> list;
    @Autowired
    LabHisReqService labHisReqService;
    @Autowired
    LabReqdetailService labReqdetailService;

    @Override
    public Result saveDetail(LabReqUnqualified labReqUnqualified) throws JsonProcessingException {
        if (ToolsUtils.isEmpty(labReqUnqualified)) {
            return Result.fail("入参异常");
        }
        int a = 0;
        Boolean b = false;
        SysUser user = RedisUserManager.getUser();
        //修改申请表信息状态
        LambdaQueryWrapper<LabProcessSet> processSetWrapper = new LambdaQueryWrapper<>();
        processSetWrapper.eq(LabProcessSet::getDelFlag, 0);
        processSetWrapper.eq(LabProcessSet::getCode, "80");
        List<LabProcessSet> processSets = processSetMapper.selectList(processSetWrapper);
        String value = "";
        if (CollectionUtils.isNotEmpty(processSets)) {
            value = processSets.get(0).getNodeName();
        }

        LambdaUpdateWrapper<LabReqMain> updateWrapper = new LambdaUpdateWrapper<>();
        updateWrapper.set(LabReqMain::getState, "80");
        updateWrapper.set(LabReqMain::getStateNa, value);
        updateWrapper.set(LabReqMain::getIsSign, null);
//        updateWrapper.set(LabReqMain::getSignTime, null);
        updateWrapper.setSql("sign_time = NULL");
        updateWrapper.set(LabReqMain::getSignerDoctor, null);
        updateWrapper.set(LabReqMain::getSignerNa, null);
        updateWrapper.eq(LabReqMain::getReqNo, labReqUnqualified.getReqNo());
        a = reqMainMapper.update(null, updateWrapper);
        //存到状态表中
        LabReqState labReqState = new LabReqState();
        LambdaQueryWrapper<LabReqState> queryStateWrapper = new LambdaQueryWrapper<>();
        queryStateWrapper.eq(LabReqState::getReqNo, labReqUnqualified.getReqNo()).eq(LabReqState::getOrgId, user.getOrgId())
                .eq(LabReqState::getDelFlag, 0);
        List<LabReqState> listState = labReqStateMapper.selectList(queryStateWrapper);
        labReqState.setSeq((long) (listState.size() + 1));
        labReqState.setOrgId(user.getOrgId());
        labReqState.setReqNo(labReqUnqualified.getReqNo());
        labReqState.setStateValue(value);
        labReqState.setStateCode("80");
        a = labReqStateMapper.insert(labReqState);
        String reasonNames = "";
        if (CollectionUtils.isNotEmpty(labReqUnqualified.getUnqualifiedDetailIds())) {
            List<LabUnqualifiedReason> labUnqualifiedReasons = unqualifiedReasonMapper.selectBatchIds(labReqUnqualified.getUnqualifiedDetailIds());
            reasonNames = labUnqualifiedReasons.stream()
                    .map(LabUnqualifiedReason::getReason) // 提取每个对象的 name 属性
                    .collect(Collectors.joining(",")); // 用逗号拼接
        }


        labReqUnqualified.setOrgId(user.getOrgId());
        labReqUnqualified.setReqNo(labReqUnqualified.getReqNo());
        labReqUnqualified.setType("0");
        labReqUnqualified.setOperator(user.getHisEmployeeCode());
        labReqUnqualified.setOperatorTime(new Date());
        labReqUnqualified.setSourceType("req");
        labReqUnqualified.setIllustrate(reasonNames);
        a = reqUnqualifiedMapper.insert(labReqUnqualified);
        if (a < 0) {
            return Result.fail("操作失败");
        }

        LambdaQueryWrapper<SysInterface> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(SysInterface::getDelFlag, 0);
        wrapper.eq(SysInterface::getIsEnable, 1);
        wrapper.eq(SysInterface::getOrgId, user.getOrgId());
        List<SysInterface> sysInterfaces = sysInterfaceMapper.selectList(wrapper);
        List<String> collect = sysInterfaces.stream().filter(o -> Objects.nonNull(o) && StringUtils.isNotBlank(o.getInterfaceUrl())).map(SysInterface::getInterfaceUrl).distinct().collect(Collectors.toList());
        //标本签收
        if (CollectionUtils.isNotEmpty(collect)) {
            /*发布报告相关*/
            for (String webUrl : collect) {
                //调用修改状态接口
                String updateUrl = webUrl + "/public/sampleReceptionCancle";
                Map<String, Object> updateMap = new HashMap<>();
                updateMap.put("reqNo", labReqUnqualified.getReqNo());
                updateMap.put("username", user.getUsername());
                updateMap.put("realname", user.getRealname());
                updateMap.put("orgId", user.getOrgId());
                String update = HttpUtil.createPost(updateUrl).setConnectionTimeout(3000).body(JSONUtil.toJsonStr(updateMap)).contentType("application/json").execute().body();
                //菏泽三院退费接口
//                String returnFeeUrl = webUrl + "/public/barcodeDelReturnFee";
//                String update11 = HttpUtil.createPost(returnFeeUrl).setConnectionTimeout(3000).body(JSONUtil.toJsonStr(updateMap)).contentType("application/json").execute().body();

                LambdaQueryWrapper<LabReqMain> lambdaQueryWrapper = new LambdaQueryWrapper<>();
                lambdaQueryWrapper.eq(LabReqMain::getReqNo, labReqUnqualified.getReqNo())
                        .eq(LabReqMain::getDelFlag, 0);
                List<LabReqMain> list = labReqMainService.list(lambdaQueryWrapper);
                if ("3".equals(list.get(0).getPatType())) {
//                    String updateUrlHl7 = webUrl + "/confimReFoundFee";
//                    HttpUtil.createPost(updateUrlHl7).setConnectionTimeout(3000).body(JSONUtil.toJsonStr(updateMap)).contentType("application/json").execute().body();
                }
            }
        }

        /*验证系统参数，标本退回时删除掉reqmain,reqdetail,labHisreq,伊通需求2025-01-10，已和萌虎讨论*/
        SysParamParam sysp1 = new SysParamParam();
        sysp1.setParamCode("xtxxcs");
        sysp1.setField("bbthsfscsqbxx");
        List<SysParamFieldValueDto> r1 = sysParamValueService.findSysParamFieldAndValueListByCode(sysp1);
        if (!r1.isEmpty()) {
            if (r1.get(0).getValue().equals("1")) {
                if (CollectionUtils.isNotEmpty(collect)) {
                    for (String webUrl : collect) {
                        String updateUrl = webUrl + "/public/updateReportStatus";
                        Map<String, Object> updateMap = new HashMap<>();
                        updateMap.put("status", "99");//消审
                        updateMap.put("reqNo", labReqUnqualified.getReqNo());
                        updateMap.put("orgId", user.getOrgId());
                        updateMap.put("username", user.getUsername());
                        updateMap.put("realname", user.getRealname());
                        String changeStatus = HttpUtil.createPost(updateUrl).setConnectionTimeout(3000).body(JSONUtil.toJsonStr(updateMap)).contentType("application/json").execute().body();
                    }
                }
                LambdaQueryWrapper<LabHisReq> lambdaQueryWrapper = new LambdaQueryWrapper<>();
                lambdaQueryWrapper.eq(LabHisReq::getReqNo, labReqUnqualified.getReqNo())
                        .eq(LabHisReq::getDelFlag, 0);
                labHisReqService.remove(lambdaQueryWrapper);

                LambdaQueryWrapper<LabReqMain> lambdaQueryWrapper1 = new LambdaQueryWrapper<>();
                lambdaQueryWrapper1.eq(LabReqMain::getReqNo, labReqUnqualified.getReqNo())
                        .eq(LabReqMain::getDelFlag, 0);
                labReqMainService.remove(lambdaQueryWrapper1);

                LambdaQueryWrapper<LabReqdetail> lambdaQueryWrapper2 = new LambdaQueryWrapper<>();
                lambdaQueryWrapper2.eq(LabReqdetail::getReqNo, labReqUnqualified.getReqNo())
                        .eq(LabReqdetail::getDelFlag, 0);
                labReqdetailService.remove(lambdaQueryWrapper2);
            }
        }


        String unqualifiedId = labReqUnqualified.getId();
        if (ToolsUtils.isNotEmpty(labReqUnqualified.getUnqualifiedDetailIds())) {
            //循环存储退回原因
            List<String> unqualifiedReasonId = labReqUnqualified.getUnqualifiedDetailIds();
            for (String s : unqualifiedReasonId) {
                LabReqUnqualifiedDetail saveDetail = new LabReqUnqualifiedDetail();
                saveDetail.setUnqualifiedReasonId(s);
                LabUnqualifiedReason labUnqualifiedReason = unqualifiedReasonMapper.selectById(s);
                String unqualifiedGroupId = labUnqualifiedReason.getUnqualifiedGroupId();
                saveDetail.setUnqualifiedGroupId(unqualifiedGroupId);
                saveDetail.setOrgId(user.getOrgId());
                saveDetail.setReqUnqualifiedId(unqualifiedId);
                b = this.save(saveDetail);
            }
            if (b) {
                return Result.succ("操作成功");
            } else {
                return Result.fail("操作失败");
            }
        }
        if (a > 0) {
            return Result.succ("操作成功");
        } else {
            return Result.fail("操作失败");
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Result saveDetailByMain(LabReqUnqualifiedDetail reqUnqualifiedDetail) {
        //存到状态表中
        Boolean b = false;
        SysUser user = RedisUserManager.getUser();
        LambdaQueryWrapper<LabReqUnqualifiedDetail> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(LabReqUnqualifiedDetail::getReqUnqualifiedId, reqUnqualifiedDetail.getReqUnqualifiedId());
        this.remove(queryWrapper);
        List<String> unqualifiedDetailNames = new ArrayList<>();
        //循环存储退回原因
        List<String> unqualifiedReasonId = reqUnqualifiedDetail.getUnqualifiedDetailIds();
        for (String s : unqualifiedReasonId) {
            LabReqUnqualifiedDetail saveDetail = new LabReqUnqualifiedDetail();
            saveDetail.setUnqualifiedReasonId(s);
            LabUnqualifiedReason labUnqualifiedReason = unqualifiedReasonMapper.selectById(s);
            unqualifiedDetailNames.add(labUnqualifiedReason.getReason());
            String unqualifiedGroupId = labUnqualifiedReason.getUnqualifiedGroupId();
            saveDetail.setUnqualifiedGroupId(unqualifiedGroupId);
            saveDetail.setOrgId(user.getOrgId());
            saveDetail.setReqUnqualifiedId(reqUnqualifiedDetail.getReqUnqualifiedId());
            b = this.save(saveDetail);
        }
        if (b) {
            String result = String.join(",", unqualifiedDetailNames);
            LabReqUnqualified labReqUnqualified = new LabReqUnqualified();
            labReqUnqualified.setId(reqUnqualifiedDetail.getReqUnqualifiedId());
            labReqUnqualified.setIllustrate(result);
            labReqUnqualified.setContactCode(reqUnqualifiedDetail.getContactCode());
            labReqUnqualified.setContactName(reqUnqualifiedDetail.getContactName());
            labReqUnqualified.setContactTime(reqUnqualifiedDetail.getContactTime());
            reqUnqualifiedMapper.updateById(labReqUnqualified);

            LabReqUnqualified labReqUnqualified1 = reqUnqualifiedMapper.selectById(reqUnqualifiedDetail.getReqUnqualifiedId());
            //调用接口将不合格记录传过去，菏泽三院需求场景
            LambdaQueryWrapper<SysInterface> wrapper = new LambdaQueryWrapper<>();
            wrapper.eq(SysInterface::getDelFlag, 0);
            wrapper.eq(SysInterface::getIsEnable, 1);
            wrapper.eq(SysInterface::getOrgId, user.getOrgId());
            List<SysInterface> sysInterfaces = sysInterfaceMapper.selectList(wrapper);
            List<String> collect = sysInterfaces.stream().filter(o -> Objects.nonNull(o) && StringUtils.isNotBlank(o.getInterfaceUrl())).map(SysInterface::getInterfaceUrl).distinct().collect(Collectors.toList());
            if (com.baomidou.mybatisplus.core.toolkit.CollectionUtils.isNotEmpty(collect)) {
                /*调用his接口*/
                for (String webUrl : collect) {
                    String updateUrl = webUrl + "/UnQualifiedSampleToHis";
                    String release = HttpUtil.createPost(updateUrl).setConnectionTimeout(3000).body(JSONUtil.toJsonStr(labReqUnqualified1)).contentType("application/json").execute().body();
                }
            }

            return Result.succ(labReqUnqualified);
        } else {
            return Result.fail("操作失败");
        }
    }

    @Override
    public Result getDetailList(LabReqUnqualifiedDetail reqUnqualifiedDetail) {
        LambdaQueryWrapper<LabReqUnqualifiedDetail> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(LabReqUnqualifiedDetail::getReqUnqualifiedId, reqUnqualifiedDetail.getReqUnqualifiedId());
        List<LabReqUnqualifiedDetail> list = this.list(queryWrapper);
        return Result.succ(1, "查询成功", list);

    }

    private List<String> getListValueMethod(String value) {
        // 去掉首尾的方括号
        String str = value.replaceAll("\\[|\\]", "");
        // 分割字符串
        String[] parts = str.split(",");
        // 创建一个列表来存储整数
        List<String> list = new ArrayList<>();
        // 遍历分割后的字符串数组，并将其转换为整数后添加到列表中
        for (String part : parts) {
            // 去掉引号
            String numStr = part.trim().replaceAll("\"", "");
            list.add(numStr);
        }
        return list;
    }
}
